<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import InsuranceContract from './components/InsuranceContract.vue'
import { unref } from 'vue'

import { Table } from '@/components/Table'

import {
  zcInsuranceOrderListApi,
  zcInsuranceOrderAddAdminApi,
  zcInsuranceOrderEditApi,
  zcInsuranceOrderDelApi,
  zcInsuranceOrderAdminExamineApi,
  zcInsuranceOrderConfirmApi,
  zcInsuranceOrderContractEditApi,
  dbInsuranceOrderDetailedListApi
  // sysRelFileBatchAddApi
} from '@/api/fa/insurance'

import { useTable } from '@/hooks/web/useTableTest'
import { ref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

const saveLoading = ref(false) //保存中的状态
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconVerify = useIcon({ icon: 'icon-park-outline:audit' })
const iconVerifyInsure = useIcon({ icon: 'uil:comment-verify' })
const iconExport = useIcon({ icon: 'bxs:file-export' })

import { useCache } from '@/hooks/web/useCache'
import { sysDictRelsApi } from '@/api/dict'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const dictRelsData = ref() // 联动数据
// const breedSubData: any = ref([]) // 品种的枚举
// const searchRef = ref() // 搜索的标签

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
// const breedGetSub = async (breed_value) => {
//   // console.log('breed_value', breed_value, !breed_value)
//   if (!breed_value) {
//     breedSubData.value = []
//   } else {
//     let breedData = dictRelsData.value.find((item) => {
//       return item.value == breed_value
//     })
//     breedSubData.value = breedData.children
//   }
// }

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcInsuranceOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

// 选择畜别的时候触发，处理品种类容
// const breedChange = (value) => {
//   breedGetSub(value)
//   const new_search = unref(searchRef)
//   new_search.setData({ ...new_search.getData(), breed_sub: '' })
// }
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 180,
    search: {
      show: false
    }
  },
  {
    field: 'code',
    label: '保险编码',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'insurance_no',
    label: '保险单号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'state',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('insurance_order_state', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.insurance_order_state
      },
      show: true
    }
  },
  {
    field: 'insurance_type',
    label: '投保类型',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('insurance_type', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.insurance_type
      },
      show: true
    }
  },
  // {
  //   field: 'breed',
  //   label: '畜别',
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return getDictLabel('breed', cellValue)
  //   },
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dict.breed,
  //       onChange: breedChange
  //     },
  //     show: true
  //   }
  // },
  // {
  //   field: 'breed_sub',
  //   label: '品种',
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return getDictLabel('breed_sub', cellValue)
  //   },
  //   width: 150,
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: breedSubData
  //     },
  //     show: true
  //   }
  // },
  {
    field: 'number',
    label: '投保资产数',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'amount',
    label: '投保金额',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150,
    search: {
      show: false
    }
  },

  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        state: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'verify':
      ElMessageBox.confirm(`是否审核？`, '审核？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 归档
          file(row.id)
        })
        .catch(() => {
          console.log('这里是取消审核')
        })
      break
    case 'insuranceContract':
      dialogTitle.value = '上传保险合同信息'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'verifyInsure':
      ElMessageBox.confirm(`是否审核？`, '保险审核？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 归档
          verifyInsure(row.id)
        })
        .catch(() => {
          console.log('这里是取消审核')
        })
      break
    case 'del':
      ElMessageBox.confirm(`删除该保险记录？`, '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.id)
        })
        .catch(() => {
          console.log('取消删除该保险记录')
        })
      break
    case 'export':
      console.log(row, '导出')
      // break
      let { data }: any = await dbInsuranceOrderDetailedListApi({
        request: {
          insurance_order_id: row.id,
          pageNo: 1,
          pageSize: '10000'
        },
        layout_data: {
          file_name: '保险申报单资产明细列表',
          column_cell_start: 'A2',
          column_data: [
            {
              title: '序号',
              width: 5,
              cell_type: 'key'
            },
            {
              title: '牧场名称',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'pasture_name'
            },
            {
              title: '保险申报单号',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'code'
            },
            {
              title: '保险类型',
              width: 20,
              cell_type: 'dict',
              dict_type: 'insurance_type',
              give_type: 'variable',
              give_value: 'insurance_type'
            },
            {
              title: '资产编号（注射）',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'asset_code'
            },
            {
              title: '资产编号（项圈）',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'asset_code_2'
            },
            {
              title: '耳标编号',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'earcon_code'
            },
            {
              title: '保险公司',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'insurance_org_name'
            },
            {
              title: '保险单号',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'insurance_no'
            },
            {
              title: '保费',
              width: 20,
              cell_type: 'number',
              give_type: 'variable',
              give_value: 'premium'
            },
            {
              title: '费率',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'rate'
            },
            {
              title: '单位保额',
              width: 20,
              cell_type: 'number',
              decimal: 2,
              give_type: 'variable',
              give_value: 'unitamount'
            },
            {
              title: '保险日期',
              width: 15,
              cell_type: 'date',
              give_type: 'variable',
              give_value: 'insurance_data'
            },
            {
              title: '投保年限',
              width: 10,
              cell_type: 'number',
              give_type: 'variable',
              give_value: 'years'
            },
            {
              title: '状态',
              width: 8,
              cell_type: 'dict',
              dict_type: 'insurance_order_state',
              give_type: 'variable',
              give_value: 'state'
            },
            {
              title: '备注',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'note'
            },
            {
              title: '创建人',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'create_user_name'
            },
            {
              title: '创建时间',
              width: 20,
              cell_type: 'datetime',
              give_type: 'variable',
              give_value: 'create_time'
            }
          ],
          custom: [
            {
              cell_type: 'string',
              cell: 'A1:R1',
              give_type: 'format',
              give_value: '保险申报单资产明细列表',
              horizontal: 'center',
              border: true,
              size: '16'
            }
          ]
        }
      })
        .catch(() => {})
        .finally(() => {
          // saveLoading.value = false
        })
      if (data) {
        window.open(data.url)

        // console.log(data, Math.ceil(data.count / 10000))
        // FormsNumber.value = Math.ceil(data.count / 10000)
      }
      break
    default:
      console.log('未知类型')
  }
}
const apiDel = async (id) => {
  let delRes = await zcInsuranceOrderDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}
const file = async (id) => {
  let delRes = await zcInsuranceOrderAdminExamineApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}
const verifyInsure = async (id) => {
  let delRes = await zcInsuranceOrderConfirmApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
// const loading = ref(false)
const ids = ref<any>([])
const checkedAll = ref(false)

const save = async () => {
  const edit = unref(editRef)
  const dataInfo = await edit?.data

  // const data = (await edit?.getFormData()) as any
  switch (actionType.value) {
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const methods = await edit?.methods
          const { getSelections } = methods
          let selectDataInfo = ref({})
          // saveLoading.value = true
          await getSelections().then((res: any) => {
            selectDataInfo.value = res
            checkedAll.value = res.allCheck.value ? res.allCheck.value : false
            if (res.allCheck.value) {
              if (res.noSelectData.value.length > 0) {
                ids.value = res.noSelectData.value.map((element) => element.id)
              }
            } else {
              if (res.selectData.value.length > 0) {
                // console.log(res.selectData.value, 'res.selectData.value')
                ids.value = res.selectData.value.map((element) => element.id)
              }
            }
          })
          const data = (await edit?.getFormData()) as any
          console.log(dataInfo, ids, data, 'vgbhjn')
          const resIn = await zcInsuranceOrderAddAdminApi({
            // my_dept_id: dataInfo.admin_dept_id,
            pasture_org_id: dataInfo.pasture_org_id,
            pasture_dept_id: dataInfo.pasture_dept_id,
            pasture_user_id: dataInfo.pasture_user_id,
            breed: edit.Search.breed ? edit.Search.breed : '',
            breed_sub: edit.Search.breed_sub ? edit.Search.breed_sub : '',
            earcon_code: edit.Search.earcon_code ? edit.Search.earcon_code : '',
            asset_code: edit.Search.asset_code ? edit.Search.asset_code : '',
            number: dataInfo.number,
            // amount: data.amount,
            // insurance_type: dataInfo.insurance_type,
            note: data.note,
            checkedAll: checkedAll.value,
            selected: ids.value,
            my_dept_id: data.pasture_dept_id
          })
            .catch(() => {})
            .finally(() => {})
          if (resIn) {
            dialogVisible.value = false
            getList()
          }
        }
      })
      break
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const methodsAdd = await edit?.methods
          const { getSelections } = methodsAdd
          let selectDataInfo = ref({})
          // saveLoading.value = true
          await getSelections().then((res: any) => {
            selectDataInfo.value = res
            checkedAll.value = res.allCheck.value ? res.allCheck.value : false
            if (checkedAll.value) {
              ids.value = res.noSelectData.value.map((element) => element.id)
            } else {
              if (res.selectData.value.length > 0) {
                ids.value = res.selectData.value.map((element) => element.id)
              }
            }
          })
          const data = (await edit?.getFormData()) as any
          console.log(dataInfo, ids, edit, 'vgbhjn')
          const resIn = await zcInsuranceOrderEditApi({
            id: dataInfo.id,
            // my_dept_id: dataInfo.admin_dept_id,
            pasture_org_id: dataInfo.pasture_org_id,
            pasture_dept_id: dataInfo.pasture_dept_id,
            pasture_user_id: dataInfo.pasture_user_id,
            // insurance_type: dataInfo.insurance_type,
            breed: edit.Search.breed ? edit.Search.breed : '',
            breed_sub: edit.Search.breed_sub ? edit.Search.breed_sub : '',
            earcon_code: edit.Search.earcon_code ? edit.Search.earcon_code : '',
            asset_code: edit.Search.asset_code ? edit.Search.asset_code : '',
            number: dataInfo.number,
            // amount: data.amount,
            note: data.note,
            checkedAll: checkedAll.value,
            selected: ids.value
          })
            .catch(() => {})
            .finally(() => {})
          if (resIn) {
            dialogVisible.value = false
            getList()
          }
        }
      })
      break
    case 'insuranceContract':
      const data = (await edit?.getFormData()) as any
      console.log(dataInfo, data, edit, 'dataInfo')
      let res = await zcInsuranceOrderContractEditApi({
        id: data.id,
        insurance_dept_id: data.insurance_dept_id,
        insurance_org_id: data.insurance_org_id,
        insurance_user_id: data.insurance_user_id,
        insurance_data: data.insurance_data,
        insurance_no: data.insurance_no,
        insurance_note: data.insurance_note,
        years: 1,
        unitAmount: data.unitAmount,
        insurance_type: dataInfo.insurance_type,
        amount: data.amount,
        rate: data.rate,
        premium: data.premium,
        number: data.number,
        pasture_org_id: data.pasture_org_id,
        pasture_dept_id: data.pasture_dept_id,
        my_org_id: wsCache.get('userInfo').default_org_id
      })
        .catch(() => {})
        .finally(() => {})
      console.log(res, 'add')
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
      break
    default:
      console.log('未知类型')
  }
}

const init = async () => {
  // 获取关联关系
  await getDictRels()
}
init()
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      :selection="false"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          v-if="row.state == '1'"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton
          v-if="row.state == '2'"
          circle
          :icon="iconEdit"
          @click="action('insuranceContract', row)"
          title="上传保险信息"
        />
        <ElButton
          v-if="row.state == '1'"
          circle
          :icon="iconVerify"
          @click="action('verify', row)"
          title="提交"
        />
        <ElButton
          v-if="row.state == '2'"
          circle
          :icon="iconVerifyInsure"
          @click="action('verifyInsure', row)"
          title="完结"
        />
        <ElButton
          v-if="row.state == '1'"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />
        <ElButton
          v-if="row.state == '3'"
          circle
          :icon="iconExport"
          @click="action('export', row)"
          title="导出明细"
        />
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle" destroy-on-close>
    <Edit v-if="actionType == 'add'" ref="editRef" />

    <Edit
      v-if="actionType == 'edit'"
      ref="editRef"
      :id="tableObject.currentRow.id"
      :current-row="tableObject.currentRow"
    />
    <InsuranceContract
      v-if="actionType == 'insuranceContract'"
      ref="editRef"
      :id="Number(tableObject.currentRow.id)"
      :current-row="tableObject.currentRow"
      :detail-schema="allSchemas.detailSchema"
    />
    <See
      v-if="actionType == 'see'"
      :id="Number(tableObject.currentRow.id)"
      :current-row="tableObject.currentRow"
      :detail-schema="allSchemas.detailSchema"
    />
    <template #footer>
      <ElButton
        v-if="
          actionType == 'add' ||
          (actionType == 'edit' && tableObject.currentRow.state == 1) ||
          actionType == 'insuranceContract'
        "
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
